import {
  call, put, all, takeLatest, select
} from 'redux-saga/effects'
import {
  GET_MY_DOCTOR_SESSTIONS,
  UPDATE_MY_DOCTOR_ACTIVE_SESSION,
  GET_MY_DOCTOR_SESSION_BY_ID,
  GET_MY_DOCTOR_MESSAGE_NUMBER,
} from '@ACTIONS/myDoctor'
import { DEFAULT_TAKE, PATIENT_TYPE } from '@CONSTANTS/common'
import api from '@API'
import { getCurrentSessionId, getMyDoctorList } from './dataSelect'

const getMyDoctorSessions = function* getSessions(action) {
  try {
    const { payload = {} } = action
    const { skip } = payload
    const list = yield select(getMyDoctorList)
    const realSkip = skip === 0 ? 0 : list.length
    const data = yield call(api.getSessions, {
      ...payload,
      type: PATIENT_TYPE.FOLLOWUP,
      take: DEFAULT_TAKE,
      skip: realSkip,
    })
    const sessions = data.Sessions || []
    yield put({
      type: GET_MY_DOCTOR_SESSTIONS.SUCCESS,
      list: sessions,
      skip,
      canLoadMyDoctors: sessions.length >= DEFAULT_TAKE
    })
  } catch (error) {
    yield put({ type: GET_MY_DOCTOR_SESSTIONS.FAILURE, error })
  }
}
const getMyDoctorSessionById = function* getSessionById(action) {
  try {
    const { sId } = action
    const currentSessionId = yield select(getCurrentSessionId);

    const result = yield call(api.getSessions, { sId, type: PATIENT_TYPE.FOLLOWUP })
    const msgCount = currentSessionId === sId ? { NewMessageCounts: 0 } : {}
    if (result?.Sessions.length) {
      yield put({
        type: UPDATE_MY_DOCTOR_ACTIVE_SESSION.REQUEST,
        updateSession: { ...result.Sessions[0], ...msgCount }
      })
    }
  } catch (error) {
    yield put({ type: UPDATE_MY_DOCTOR_ACTIVE_SESSION.FAILURE, error })
  }
}
const getMyDoctorMessageNum = function* getMyDoctorMessageNum(action) {
  try {
    const currentSessionId = yield select(getCurrentSessionId);
    const { sId } = action
    if (currentSessionId && currentSessionId === sId) return
    const result = yield call(api.getTotalNewMessageNumber, { type: PATIENT_TYPE.FOLLOWUP });
    yield put({
      type: GET_MY_DOCTOR_MESSAGE_NUMBER.SUCCESS,
      num: result
    })
  } catch (error) {
    yield put({ type: GET_MY_DOCTOR_MESSAGE_NUMBER.FAILURE, error })
  }
}
export default function* rootSaga() {
  yield all([
    takeLatest(GET_MY_DOCTOR_SESSTIONS.REQUEST, getMyDoctorSessions),
    takeLatest(GET_MY_DOCTOR_SESSION_BY_ID.REQUEST, getMyDoctorSessionById),
    takeLatest(GET_MY_DOCTOR_MESSAGE_NUMBER.REQUEST, getMyDoctorMessageNum),
  ])
}
